package com.jh.paymentchannel.service;

import java.math.RoundingMode;
import java.net.URI;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.util.AesUtils;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.ump.paygate.v40.HttpRequest;
import com.jnewsdk.util.SignUtil;

import cn.jh.common.tools.Log;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.Md5Util;
import net.sf.json.JSONObject;
@Service
public class SFTopupRequest implements TopupRequest{
private static final Logger log = LoggerFactory.getLogger(SFTopupRequest.class);
	
		@Autowired
		Util util;
		
		@Value("${payment.ipAddress}")
		private String ipAddress;
		
		private String req_url = "http://api.shangfudata.com/gate/wx/spay";
		
		private String merchant_key = "753F3812342D42FA83D79EDF6E02FCA8";
		
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request,
			String amount, String ordercode, String orderdesc, String extra,
			String notifyurl, String returnurl, String channelParam)
			throws Exception {
		Map maps = new HashMap();
		if(amount.contains(".")) {
			if(amount.substring(amount.indexOf("."), amount.length()).length()<3) {
				amount = amount.substring(0, amount.indexOf("."))+amount.substring(amount.length()-1, amount.length())+"0";
			}else {
				amount = amount.substring(0, amount.indexOf("."))+amount.substring(amount.length()-2, amount.length());
			}
		}else {
			amount = amount+"00";
		}
		log.info("=====================channelParam=================="+channelParam);
		/**根据订单号获取相应的订单*/
		String idcardJJ = null;//借记卡账户身份证号
		String userNameJJ = null;//借记卡用户姓名
		long userid ;//用户ID
		String bankNameJJ = null;//借记卡银行名
		String cardNo = null;//借记卡卡号
		String lineNoJJ = null;//借记卡联行行号
		String telphone = null;//借记卡预留手机号
		String bankBranchName = null;//开户支行名称
		String desc = null;//显示页面描述
		String brandname = null;//商品名称,用于显示在支付界面 
		String province = null;
		String city = null;
		//String rate ;//结算费率(实体类型为BigDecimal)
		String channelid = null;
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/transactionclear/payment/query/ordercode--RESULT================"+result);
		JSONObject jsonObject =  JSONObject.fromObject(result);
		JSONObject resultObj  =  jsonObject.getJSONObject("result");
		desc = resultObj.getString("desc");
		int number = (int)(1+Math.random()*4);
		if(number==1)
			desc = "餐饮消费";
		if(number==2)
			desc = "酒店消费";
		if(number==3)
			desc = "服装消费";
		if(number==4)
			desc = "娱乐消费";
		userid = resultObj.getLong("userid");
		String brandid = resultObj.getString("brandid");
		channelid = resultObj.getString("channelid");
		String leg_phone = resultObj.getString("phone");
		String bankcard = resultObj.getString("bankcard");
		String rate = resultObj.getString("rate");	
		Double extraFee = resultObj.getDouble("extraFee");//额外费用
		DecimalFormat df = new DecimalFormat("0");
		df.setRoundingMode(RoundingMode.DOWN);
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", String.valueOf(userid));
		result = restTemplate.postForObject(url, requestEntity, String.class);
		String respCode = "";
		log.info("接口/v1.0/user/bank/default/userid--RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
			respCode  =  jsonObject.getString("resp_code");
		} catch (Exception e) {
			Map map = new HashMap();
			log.error("查询结算卡异常" + e.getMessage());
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "用户未设置默认提现卡");
			return map;
		}
		
		if(!"000000".equals(respCode)){
			Map map = new HashMap();
			map.put("resp_code", "failed");
			map.put("resp_message", "用户未设置默认提现卡");
			return map;
		}
		
//		if(null==jsonObject.get("result")||jsonObject.get("result").equals("")){
//			Map map = new HashMap();
//			map.put("resp_code", "failed");
//			map.put("resp_message", "用户未设置默认提现卡");
//			return map;
//		}
		
		province = resultObj.getString("province");
		city = resultObj.getString("city");
		bankBranchName = resultObj.getString("bankBranchName");//开户支行名称
		 bankNameJJ = resultObj.getString("bankName");//借记卡银行名
		 cardNo = resultObj.getString("cardNo");//借记卡卡号
		 lineNoJJ = resultObj.getString("lineNo");//借记卡联行行号
		 telphone = resultObj.getString("phone");//借记卡预留手机号
		 userNameJJ = resultObj.getString("userName");//借记卡用户姓名
		 idcardJJ = resultObj.getString("idcard");//借记卡账户身份证号
		 
	    restTemplate=new RestTemplate();
		 uri = util.getServiceUrl("user", "error url request!");
		 url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankcard);
		requestEntity.add("type", "0");
		 try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
			 jsonObject =  JSONObject.fromObject(result);
			 resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询用户信用卡信息有误======"+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "查询用户信用卡信息出错啦");
			return maps;
		}
		if(resultObj==null){
			return null;
		}
		 String expiredTime = resultObj.getString("expiredTime");//付款信用卡有效期,格式YYMM
		 if(expiredTime.contains("/")) {
			 String start = expiredTime.substring(0, 2);
			 String end = expiredTime.substring(3, 5);
			 expiredTime = start+end;
		 }else {
			 
			 String start = expiredTime.substring(0, 2);
			 String end = expiredTime.substring(2, 4);
			 expiredTime = end+start;
		 }
		 String securityCode = resultObj.getString("securityCode");//付款信用卡安全码
		 String phoneX = resultObj.getString("phone"); //预留信用卡手机号码
		 String nature = resultObj.getString("nature");//充值卡类型
		 //String idcard = resultObj.getString("idcard");//身份证号
		 String bankNameX = resultObj.getString("bankName");//信用卡银行名
		 String cardType = "CREDIT";
		 if(nature.contains("借记"))
			 cardType = "DEBIT";
		 /**获取银行编号*/
		 restTemplate=new RestTemplate();
		 uri = util.getServiceUrl("user", "error url request!");
		 url = uri.toString() + "/v1.0/user/bank/number/name";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("bank_name", bankNameX);
		 try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("RESULT================"+result);
			 jsonObject =  JSONObject.fromObject(result);
			 resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("获取银行编号出错啦========"+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "获取银行编号出错啦");
			return maps;
		}
		 String bankNumberX = null;
		 Map mapp = new HashMap();
		if(resultObj.containsKey("bankNumber")){
			bankNumberX =  resultObj.getString("bankNumber");
		}else {
			mapp.put("message", "不支持该银行卡");
			mapp.put("resp_code", "failed");	
			mapp.put("channel_type", "sf_pay");
			return mapp;
		}
		 
		 uri = util.getServiceUrl("user", "error url request!");
		 String road = uri.toString() + "/v1.0/user/brandrate/query";
		 requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("channel_id", channelid);
		requestEntity.add("brand_id", brandid);
		 restTemplate=new RestTemplate();
		String resultObjx;
		try {
			resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
			log.info("接口/v1.0/user/brandrate/query--RESULT================"+resultObjx);
			 jsonObject =  JSONObject.fromObject(resultObjx);
			 resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询贴牌费率有误====="+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "查询贴牌费率出错啦");
			return maps;
		}
		 int withdrawFee = resultObj.getInt("withdrawFee");
		 withdrawFee = withdrawFee*100;
		 log.info("======================withdrawFee======================="+withdrawFee);
		 uri = util.getServiceUrl("paymentchannel", "error url request!");
		 road = uri.toString() + "/v1.0/paymentchannel/branchno/findbybankname";
		
		 requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("bankName", bankNameJJ);
		 restTemplate=new RestTemplate();
		 try {
			resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
			log.info("接口/v1.0/paymentchannel/branchno/findbybankname--RESULT================"+resultObjx);
			 jsonObject =  JSONObject.fromObject(resultObjx);
		} catch (Exception e) {
			log.error("查询银行编号有误======"+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "查询银行编号信息出错啦");
			return maps;
		}
		 
		 if(!jsonObject.containsKey("result")) {
			 log.info("======================编号不存在======================="+bankNameJJ);
			 mapp.put("message", "银行编号不存在");
			 mapp.put("resp_code", "failed");	
			 mapp.put("channel_type", "sf_pay");
			 return mapp;
		 }
		 JSONObject relt = jsonObject.getJSONObject("result");
		 log.info("======================relt======================="+relt);
		 String bankNumber = relt.getString("bankNo");
		 
		 uri = util.getServiceUrl("paymentchannel", "error url request!");
		 road = uri.toString() + "/v1.0/paymentchannel/sfauth/findbyphone";
		 requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("phone", leg_phone);
		 restTemplate=new RestTemplate();
		 try {
			resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
			log.info("接口/v1.0/paymentchannel/sfauth/findbyphone--RESULT================"+resultObjx);
			 jsonObject =  JSONObject.fromObject(resultObjx);
		} catch (Exception e) {
			log.error("查询用户进件信息有误====="+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "查询用户进件信息出错啦");
			return maps;
		}
		 String settleRate = null;
		 String accNo = null;
		 String mrtNo = null;
		 String secretKey = null;
		 String dataKey = null;
		 String busiType1 = null;
		 String busiType2 = null;
		 String extratype = null;
		 if(jsonObject.containsKey("result")) {
			 resultObj  =  jsonObject.getJSONObject("result");
			 settleRate = resultObj.getString("settleRate");
			 accNo = resultObj.getString("accNo");
			 mrtNo = resultObj.getString("mrtNo");
			 secretKey = resultObj.getString("secretKey");
			 dataKey = resultObj.getString("dataKey");
			 busiType1 = resultObj.getString("typeMp");
			 busiType2 = resultObj.getString("typeEpays");
			 extratype = resultObj.getString("extraRateType");
		 }
		 String mcht_no = null;
		if(!jsonObject.containsKey("result")) {
			Map<String, Object> map = new TreeMap<String, Object>(
		         new Comparator<String>() {
		             @Override
					public int compare(String obj1, String obj2) {
		             return obj1.compareTo(obj2);
		           }
		        });
				map.put("sp_id", "1102-2");  
				map.put("mcht_name", "个体工商户"+userNameJJ);  
				map.put("mcht_short_name", "个体工商户");
				map.put("address", "上海");  //详细地址  @
				map.put("leg_name", userNameJJ);
				map.put("leg_phone", leg_phone);  
				//map.put("leg_email", "");
				map.put("acc_no", cardNo);
				map.put("acc_bank_name", bankNameJJ);
				map.put("acc_bank_no", bankNumber);//结算银行联行号
				map.put("service_tel", telphone);
				map.put("id_type", "01");
				map.put("id_no", idcardJJ);
				map.put("nonce_str", ordercode);
			//拼接字符串
			String signMsg = SignUtil.getSignMsg(map, null);
			log.info("拼接字符串——signMsg@"+signMsg);
		    String key = merchant_key;
		    String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
		    System.out.println("signature:"+signature);
		    map.put("sign", signature);  
		    log.info("---------------------——map@"+map.toString());
		    signMsg = SignUtil.getSignMsg(map, null);
			 url = "http://api.shangfudata.com/gate/msvr/mbreg";
			log.info("--------------------——signMsg@"+signMsg);
			String msg = HttpRequest.sendPost(url, signMsg);
			JSONObject json = JSONObject.fromObject(msg); 
			log.info("--------------------——json@"+json);
			
			if("SUCCESS".equals(json.getString("status"))) {
				if("SUCCESS".equals(json.getString("result_code"))) {
					secretKey = json.getString("secretKey");
					dataKey = json.getString("dataKey");
					mcht_no = json.getString("mcht_no");
					mrtNo = mcht_no;
					map = new TreeMap<String, Object>(
					         new Comparator<String>() {
					             @Override
								public int compare(String obj1, String obj2) {
					             return obj1.compareTo(obj2);
					           }
					        });
							map.put("sp_id", "1102-2");  
							map.put("mcht_no", mcht_no);  
							map.put("busi_type", "MP");
							map.put("settle_type", "REAL_PAY");  
							map.put("settle_rate", rate);
							map.put("extra_rate_type", "AMOUNT");  
							map.put("extra_rate", df.format(extraFee*100));
							map.put("nonce_str", ordercode);
						 signMsg = SignUtil.getSignMsg(map, null);
						log.info("拼接字符串——signMsg@"+signMsg);
					     key = merchant_key;
					     signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
					    System.out.println("signature:"+signature);
					    map.put("sign", signature);  
					    log.info("---------------------——map@"+map.toString());
					    signMsg = SignUtil.getSignMsg(map, null);
						 url = "http://api.shangfudata.com/gate/msvr/busiopen";
						log.info("--------------------——signMsg@"+signMsg);
						 msg = HttpRequest.sendPost(url, signMsg);
						json = JSONObject.fromObject(msg); 
						if("SUCCESS".equals(json.getString("status"))) {
							if("SUCCESS".equals(json.getString("result_code"))) {
								 uri = util.getServiceUrl("paymentchannel", "error url request!");
								 road = uri.toString() + "/v1.0/paymentchannel/sfauth/add";
								 requestEntity  = new LinkedMultiValueMap<String, String>();
								 requestEntity.add("phone", leg_phone);
								 requestEntity.add("mrtNo", mcht_no);
								 requestEntity.add("secretKey", secretKey);
								 requestEntity.add("dataKey", dataKey);
								 requestEntity.add("accBankName", bankNameJJ);
								 requestEntity.add("accBankNo", bankNumber);
								 requestEntity.add("card", idcardJJ);
								 requestEntity.add("settleRate", rate);
								 requestEntity.add("extraRateType", df.format(extraFee*100));//额外手续费
								 requestEntity.add("extraRate", "0");//额外费率
								 requestEntity.add("name", userNameJJ);
								 requestEntity.add("bankPhone", telphone);
								 requestEntity.add("accNo", cardNo);
								 restTemplate=new RestTemplate();
								 log.info("/v1.0/paymentchannel/sfauth/add--参数================"+requestEntity.toString());
								 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
								 log.info("/v1.0/paymentchannel/sfauth/add--RESULT================"+resultObjx);
								 jsonObject =  JSONObject.fromObject(resultObjx);
								 if(!jsonObject.containsKey("result")) {
									 mapp.put("message", "注册信息保存失败！");
										mapp.put("resp_code", "failed");	
										mapp.put("channel_type", "sf_pay");
										return mapp;
								 }
							}else {
								mapp.put("message", json.getString("err_msg"));
								mapp.put("resp_code", "failed");	
								mapp.put("channel_type", "sf_pay");
								return mapp;
							}
						}else {
							mapp.put("message", json.getString("message"));
							mapp.put("resp_code", "failed");	
							mapp.put("channel_type", "sf_pay");
							return mapp;
						}
						uri = util.getServiceUrl("paymentchannel", "error url request!");
						 road = uri.toString() + "/v1.0/paymentchannel/sfauth/update";
						 requestEntity  = new LinkedMultiValueMap<String, String>();
						 requestEntity.add("phone", leg_phone);
						 requestEntity.add("typeMp", "1");
						 restTemplate=new RestTemplate();
						 log.info("/v1.0/paymentchannel/sfauth/update--参数================"+requestEntity.toString());
						 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
						 log.info("/v1.0/paymentchannel/sfauth/update--RESULT================"+resultObjx);
						 jsonObject =  JSONObject.fromObject(resultObjx);
						 if(!"000000".equals(jsonObject.getString("resp_code"))) {
							 mapp.put("message", "修改开通业务失败！");
								mapp.put("resp_code", "failed");	
								mapp.put("channel_type", "sf_pay");
								return mapp;
						 }
					 
				}else {
					mapp.put("message", json.getString("err_msg"));
					mapp.put("resp_code", "failed");	
					mapp.put("channel_type", "sf_pay");
					return mapp;
				}
			}else {
				mapp.put("message", json.getString("message"));
				mapp.put("resp_code", "failed");	
				mapp.put("channel_type", "sf_pay");
				return mapp;
			}
		}else {
			if(!settleRate.equals(rate)) {
				Map<String, Object> map = new TreeMap<String, Object>(
				         new Comparator<String>() {
				             @Override
							public int compare(String obj1, String obj2) {
				             return obj1.compareTo(obj2);
				           }
				        });
					map.put("sp_id", "1102-2");  
					map.put("mcht_no", mrtNo);  
					if(channelParam.trim().equalsIgnoreCase("kj")) {
						map.put("busi_type", "EPAYS");
					}else {
						map.put("busi_type", "MP");
					}
					map.put("settle_type", "REAL_PAY");  
					map.put("settle_rate", rate);
					map.put("extra_rate_type", "AMOUNT");  
					map.put("extra_rate", df.format(extraFee*100));	
					map.put("nonce_str", ordercode);
					//拼接字符串
					String signMsg = SignUtil.getSignMsg(map, null);
					log.info("拼接字符串——signMsg@"+signMsg);
					String key = "D581F1B300114D7D9B03CFB4E6992338";
					String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
				    System.out.println("signature:"+signature);
				    map.put("sign", signature);  
				    log.info("---------------------——map@"+map.toString());
				    signMsg = SignUtil.getSignMsg(map, null);
					 url = "http://api.shangfudata.com/gate/msvr/busiratemodify";
					log.info("--------------------——signMsg@"+signMsg);
					String msg = HttpRequest.sendPost(url, signMsg);
					JSONObject json = JSONObject.fromObject(msg); 
					log.info("--------------------——json@"+json);
					if("SUCCESS".equals(json.getString("status"))) {
						if("SUCCESS".equals(json.getString("result_code"))) {
							uri = util.getServiceUrl("paymentchannel", "error url request!");
							 road = uri.toString() + "/v1.0/paymentchannel/sfauth/update";
							 requestEntity  = new LinkedMultiValueMap<String, String>();
							 requestEntity.add("phone", leg_phone);
							 requestEntity.add("settleRate", rate);
							 restTemplate=new RestTemplate();
							 log.info("/v1.0/paymentchannel/sfauth/update--参数================"+requestEntity.toString());
							 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
							 log.info("/v1.0/paymentchannel/sfauth/update--RESULT================"+resultObjx);
							 jsonObject =  JSONObject.fromObject(resultObjx);
							 if(!"000000".equals(jsonObject.getString("resp_code"))) {
								 mapp.put("message", "修改费率失败！");
									mapp.put("resp_code", "failed");	
									mapp.put("channel_type", "sf_pay");
									return mapp;
							 }
						}else {
							mapp.put("message", json.getString("err_msg"));
							mapp.put("resp_code", "failed");	
							mapp.put("channel_type", "sf_pay");
							return mapp;
						}
					}else {
						mapp.put("message", json.getString("message"));
						mapp.put("resp_code", "failed");	
						mapp.put("channel_type", "sf_pay");
						return mapp;
					}
			}
			if(!accNo.equals(cardNo)) {
				Map<String, Object> map = new TreeMap<String, Object>(
				         new Comparator<String>() {
				             @Override
							public int compare(String obj1, String obj2) {
				             return obj1.compareTo(obj2);
				           }
				        });
						map.put("sp_id", "1102-2");  
						map.put("mcht_no", mrtNo);  
						map.put("acc_no", cardNo);
						map.put("acc_bank_name", bankNameJJ);
						map.put("acc_bank_no", bankNumber);//结算银行联行号
						map.put("service_tel", telphone);
						map.put("nonce_str", ordercode);
					String signMsg = SignUtil.getSignMsg(map, null);
					log.info("拼接字符串——signMsg@"+signMsg);
					String key = "EBA7EBDCDCFF400AA6BA4B7C89CC6392";
					String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
				    System.out.println("signature:"+signature);
				    map.put("sign", signature);  
				    log.info("---------------------——map@"+map.toString());
				    signMsg = SignUtil.getSignMsg(map, null);
					 url = "http://api.shangfudata.com/gate/msvr/modify/mbsettle";
					log.info("--------------------——signMsg@"+signMsg);
					String msg = HttpRequest.sendPost(url, signMsg);
					JSONObject json = JSONObject.fromObject(msg); 
					log.info("--------------------——json@"+json);
					if("SUCCESS".equals(json.getString("status"))) {
						if("SUCCESS".equals(json.getString("result_code"))) {
							uri = util.getServiceUrl("paymentchannel", "error url request!");
							 road = uri.toString() + "/v1.0/paymentchannel/sfauth/update";
							 requestEntity  = new LinkedMultiValueMap<String, String>();
							 requestEntity.add("phone", leg_phone);
							 requestEntity.add("accNo", cardNo);
							 restTemplate=new RestTemplate();
							 log.info("/v1.0/paymentchannel/sfauth/update--参数================"+requestEntity.toString());
							 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
							 log.info("/v1.0/paymentchannel/sfauth/update--RESULT================"+resultObjx);
							 jsonObject =  JSONObject.fromObject(resultObjx);
							 if(!"000000".equals(jsonObject.getString("resp_code"))) {
								 mapp.put("message", "修改结算卡号失败！");
									mapp.put("resp_code", "failed");	
									mapp.put("channel_type", "sf_pay");
									return mapp;
							 }
						}else {
							mapp.put("message", json.getString("err_msg"));
							mapp.put("resp_code", "failed");	
							mapp.put("channel_type", "sf_pay");
							return mapp;
						}
					}else {
						mapp.put("message", json.getString("message"));
						mapp.put("resp_code", "failed");	
						mapp.put("channel_type", "sf_pay");
						return mapp;
					}
			}
			if(!df.format(extraFee*100).equals(extratype)) {
				Map<String, Object> map = new TreeMap<String, Object>(
				         new Comparator<String>() {
				             @Override
							public int compare(String obj1, String obj2) {
				             return obj1.compareTo(obj2);
				           }
				        });
					map.put("sp_id", "1102-2");  
					map.put("mcht_no", mrtNo);  
					if(channelParam.trim().equalsIgnoreCase("kj")) {
						map.put("busi_type", "EPAYS");
					}else {
						map.put("busi_type", "MP");
					}
					map.put("settle_type", "REAL_PAY");  
					map.put("settle_rate", rate);
					map.put("extra_rate_type", "AMOUNT");  
					map.put("extra_rate", df.format(extraFee*100));	
					map.put("nonce_str", ordercode);
					//拼接字符串
					String signMsg = SignUtil.getSignMsg(map, null);
					log.info("拼接字符串——signMsg@"+signMsg);
					String key = "D581F1B300114D7D9B03CFB4E6992338";
					String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
				    System.out.println("signature:"+signature);
				    map.put("sign", signature);  
				    log.info("---------------------——map@"+map.toString());
				    signMsg = SignUtil.getSignMsg(map, null);
					 url = "http://api.shangfudata.com/gate/msvr/busiratemodify";
					log.info("--------------------——signMsg@"+signMsg);
					String msg = HttpRequest.sendPost(url, signMsg);
					JSONObject json = JSONObject.fromObject(msg); 
					log.info("--------------------——json@"+json);
					if("SUCCESS".equals(json.getString("status"))) {
						if("SUCCESS".equals(json.getString("result_code"))) {
							uri = util.getServiceUrl("paymentchannel", "error url request!");
							 road = uri.toString() + "/v1.0/paymentchannel/sfauth/update";
							 requestEntity  = new LinkedMultiValueMap<String, String>();
							 requestEntity.add("phone", leg_phone);
							 requestEntity.add("extraRateType", df.format(extraFee*100));
							 restTemplate=new RestTemplate();
							 log.info("/v1.0/paymentchannel/sfauth/update--参数================"+requestEntity.toString());
							 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
							 log.info("/v1.0/paymentchannel/sfauth/update--RESULT================"+resultObjx);
							 jsonObject =  JSONObject.fromObject(resultObjx);
							 if(!"000000".equals(jsonObject.getString("resp_code"))) {
								 mapp.put("message", "修改手续费失败！");
									mapp.put("resp_code", "failed");	
									mapp.put("channel_type", "sf_pay");
									return mapp;
							 }
						}else {
							mapp.put("message", json.getString("err_msg"));
							mapp.put("resp_code", "failed");	
							mapp.put("channel_type", "sf_pay");
							return mapp;
						}
					}else {
						mapp.put("message", json.getString("message"));
						mapp.put("resp_code", "failed");	
						mapp.put("channel_type", "sf_pay");
						return mapp;
					}
			}
		}
		if(channelParam.trim().equalsIgnoreCase("kj")) {
			if(null==busiType2||"null".equals(busiType2)) {
			Map<String, Object> map2 = new TreeMap<String, Object>(
		         new Comparator<String>() {
		             @Override
					public int compare(String obj1, String obj2) {
		             return obj1.compareTo(obj2);
		           }
		        });
				map2.put("sp_id", "1102-2");  
				map2.put("mcht_no", mrtNo);  
				map2.put("busi_type", "EPAYS");
				map2.put("settle_type", "REAL_PAY");  
				map2.put("settle_rate", rate);
				map2.put("extra_rate_type", "AMOUNT");  
				map2.put("extra_rate", df.format(extraFee*100));
				map2.put("nonce_str", ordercode);
			String signMsg = SignUtil.getSignMsg(map2, null);
			log.info("拼接字符串——signMsg@"+signMsg);
		    String key = merchant_key;
		    String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
		    System.out.println("signature:"+signature);
		    map2.put("sign", signature);  
		    log.info("---------------------——map@"+map2.toString());
		    signMsg = SignUtil.getSignMsg(map2, null);
			 url = "http://api.shangfudata.com/gate/msvr/busiopen";
			log.info("--------------------——signMsg@"+signMsg);
			String msg = HttpRequest.sendPost(url, signMsg);
			JSONObject json = JSONObject.fromObject(msg); 
			if("SUCCESS".equals(json.getString("status"))) {
				if("SUCCESS".equals(json.getString("result_code"))) {
					uri = util.getServiceUrl("paymentchannel", "error url request!");
					 road = uri.toString() + "/v1.0/paymentchannel/sfauth/update";
					 requestEntity  = new LinkedMultiValueMap<String, String>();
					 requestEntity.add("phone", leg_phone);
					 requestEntity.add("typeEpays", "1");
					 restTemplate=new RestTemplate();
					 log.info("/v1.0/paymentchannel/sfauth/update--参数================"+requestEntity.toString());
					 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
					 log.info("/v1.0/paymentchannel/sfauth/update--RESULT================"+resultObjx);
					 jsonObject =  JSONObject.fromObject(resultObjx);
					 if(!"000000".equals(jsonObject.getString("resp_code"))) {
						 mapp.put("message", "修改开通业务失败！");
							mapp.put("resp_code", "failed");	
							mapp.put("channel_type", "sf_pay");
							return mapp;
					 }
				}else {
					mapp.put("message", json.getString("err_msg"));
					mapp.put("resp_code", "failed");	
					mapp.put("channel_type", "sf_pay");
					return mapp;
				}
			}else {
				mapp.put("message", json.getString("message"));
				mapp.put("resp_code", "failed");	
				mapp.put("channel_type", "sf_pay");
				return mapp;
			}
			}
			
			Map<String, Object> map = new TreeMap<String, Object>(
			         new Comparator<String>() {
			             @Override
						public int compare(String obj1, String obj2) {
			             return obj1.compareTo(obj2);
			           }
			        });
				if("DEBIT".equalsIgnoreCase(cardType)) {
					map.put("sp_id", "1102-2");  
					map.put("mch_id", mrtNo);  
					map.put("out_trade_no", ordercode);
					map.put("total_fee", amount);  
					map.put("body", desc);
					map.put("notify_url", ipAddress+"/v1.0/paymentchannel/topup/sf/notify_call");  
					map.put("id_type", "01");	
					map.put("acc_bank_name", bankNameX);
					map.put("acct_type", cardType);  
					map.put("acc_name", userNameJJ);  
					map.put("acc_no", bankcard);
					map.put("mobile", phoneX);  
					map.put("id_no", idcardJJ);
					map.put("bank_code", bankNumberX);  
					map.put("nonce_str", ordercode);

				}else {
					map.put("sp_id", "1102-2");  
					map.put("mch_id", mrtNo);  
					map.put("out_trade_no", ordercode);
					map.put("total_fee", amount);  
					map.put("body", desc);
					map.put("notify_url", ipAddress+"/v1.0/paymentchannel/topup/sf/notify_call");  
					map.put("id_type", "01");	
					map.put("acc_bank_name", bankNameX);
					map.put("acct_type", cardType);  
					map.put("acc_name", userNameJJ);  
					map.put("acc_no", bankcard);
					map.put("mobile", phoneX);  
					map.put("id_no", idcardJJ);
					map.put("bank_code", bankNumberX);  
					map.put("expire_date", expiredTime);	
					map.put("cvv", securityCode);
					map.put("nonce_str", ordercode);
					
				}
				//拼接字符串
				String signMsg = SignUtil.getSignMsg(map, null);
				log.info("拼接字符串——signMsg@"+signMsg);
				String key = secretKey;
				String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
			    System.out.println("signature:"+signature);
			    log.info("-------------------------------—dataKey="+dataKey);
			    String data = null;
			    if("DEBIT".equalsIgnoreCase(cardType)) {
			    	data = "?mch_id="+mrtNo+"&out_trade_no="+ordercode+"&total_fee="+amount+"&body="+URLEncoder.encode(desc, "UTF-8")
			    	+"&acc_bank_name="+URLEncoder.encode(bankNameX, "UTF-8")+"&acc_name="+AesUtils.aesEn128(userNameJJ, dataKey)
			    	+"&acc_no="+AesUtils.aesEn128(bankcard, dataKey)+"&mobile="+AesUtils.aesEn128(phoneX, dataKey)+"&id_no="+AesUtils.aesEn128(idcardJJ, dataKey)
			    	+"&bank_code="+bankNumberX+"&nonce_str="+ordercode+"&sign="+signature+"&phoneX="+phoneX+"&acct_type="+cardType+"&secretKey="+secretKey;
			    	log.info("-------------------------------—data="+data);
			    }else {
			    	data = "?mch_id="+mrtNo+"&out_trade_no="+ordercode+"&total_fee="+amount+"&body="+URLEncoder.encode(desc, "UTF-8")
			    	+"&acc_bank_name="+URLEncoder.encode(bankNameX, "UTF-8")+"&acc_name="+AesUtils.aesEn128(userNameJJ, dataKey)
			    	+"&acc_no="+AesUtils.aesEn128(bankcard, dataKey)+"&mobile="+AesUtils.aesEn128(phoneX, dataKey)+"&id_no="+AesUtils.aesEn128(idcardJJ, dataKey)
			    	+"&bank_code="+bankNumberX+"&expire_date="+AesUtils.aesEn128(expiredTime, dataKey)+"&cvv="
			    	+AesUtils.aesEn128(securityCode, dataKey)+"&nonce_str="+ordercode+"&sign="+signature+"&phoneX="+phoneX+"&acct_type="+cardType+"&secretKey="+secretKey;
			    	log.info("-------------------------------—data="+data);
			    }
			url = ipAddress+"/v1.0/paymentchannel/topup/sfkj"+data;
			mapp.put("resp_code", "success");
			mapp.put("channel_type", "sf_pay");
			mapp.put("url", url);
			return mapp;
		}
		Map<String, Object> map = new TreeMap<String, Object>(
		         new Comparator<String>() {
		             @Override
					public int compare(String obj1, String obj2) {
		             return obj1.compareTo(obj2);
		           }
		        });
		if(channelParam.trim().equalsIgnoreCase("ali")) {
			map.put("mcht_no", mrtNo);  
			map.put("trade_no",ordercode);  
			map.put("notify_url",ipAddress+"/v1.0/paymentchannel/topup/sf/notify_call");    
			map.put("totalAmount", amount);		
			map.put("subject", desc); 
			req_url = "http://api.shangfudata.com/gate/alipay/spay";
		}else {
			map.put("sp_id", "1102-2");  
			map.put("mch_id", mrtNo);  
			map.put("out_trade_no",ordercode);  
			map.put("body", desc); 
			map.put("total_fee", amount);		
			map.put("mch_create_ip", request.getLocalAddr());  
			map.put("notify_url",ipAddress+"/v1.0/paymentchannel/topup/sf/notify_call");    
			map.put("nonce_str", ordercode);   
			req_url = "http://api.shangfudata.com/gate/wx/spay";
		}	
		//拼接字符串
		String signMsg = SignUtil.getSignMsg(map, null);
		log.info("拼接字符串——signMsg@"+signMsg);
		String key = secretKey;
		log.info("=================key==============="+secretKey);
		String signature = Md5Util.getMD5(signMsg+"&key="+key).toUpperCase(); 
	    System.out.println("signature:"+signature);
	    map.put("sign", signature);  
	    log.info("---------------------——map@"+map.toString());
	    signMsg = SignUtil.getSignMsg(map, null);
		 url = req_url;
		 log.info("--------------------——req_url@"+req_url);
		log.info("--------------------——signMsg@"+signMsg);
		String msg = HttpRequest.sendPost(url, signMsg);
		JSONObject json = JSONObject.fromObject(msg);  
		log.info("--------------------——json@"+json);
		if(channelParam.equalsIgnoreCase("ali")) {
			if("0".equals(json.getString("status"))&&"000000".equals(json.getString("resultCode"))) {
				//mapp.put("url", json.getString("codeImgUrl"));
				mapp.put("url", json.getString("qrCode"));
				mapp.put("resp_code", "success");	
				mapp.put("channel_type", "sf_pay");
			}else {
				mapp.put("message", json.getString("resultMsg"));
				mapp.put("resp_code", "failed");	
				mapp.put("channel_type", "sf_pay");
			}
		}else {
			if("SUCCESS".equals(json.getString("status"))) {
				if("SUCCESS".equals(json.getString("result_code"))) {
					mapp.put("url", json.getString("code_url"));
					mapp.put("resp_code", "success");	
					mapp.put("channel_type", "sf_pay");
				}else {
					mapp.put("message", json.getString("err_msg"));
					mapp.put("resp_code", "failed");	
					mapp.put("channel_type", "sf_pay");
				}
			}else {
				mapp.put("message", json.getString("message"));
				mapp.put("resp_code", "failed");	
				mapp.put("channel_type", "sf_pay");
			}
		}
		return mapp;  
	    
	}
	
}
